<?php
//用户扫描绑定时回调处理
header("content-type:text/html;charset=utf8");
$code = $_GET['code'];
$sn = $_GET['sn'];
$authorize_token = authorize_token($code);
weixin_binding_sn($authorize_token['openid'],$sn);
$voucher_token = voucher_token();
//获取用户信息 判断是否关注公众号
$user_info = get_user_info($voucher_token['access_token'],$authorize_token['openid']);
//如果此微信绑定过账户并且关注了微信公众号进行模板消息推送通知绑定成功
if (check_openid_binding_account($authorize_token['openid'])) {
    file_get_contents("https://pay.hispot.cn/gitscan/pushLoginInfo.php?openid=".$openid);
    data_synchro_old_database($authorize_token['openid']);
    if($user_info['subscribe']==1){
        sendMessage($authorize_token['openid'],$voucher_token['access_token'],$sn);
        echo "<script>alert('恭喜您已经完成绑定操作，现在去设备端进行登录吧！');location.href='https://pay.hispot.cn/gitscan/h5/success.php'</script>";
        exit;
    }else{ 
        //如果此微信绑定过账户 但是未关注公众号 进行引导关注
        echo "<script>alert('恭喜您已经完成绑定操作，现在去设备端进行登录吧');location.href='https://pay.hispot.cn/gitscan/h5/success.php'</script>";
        exit;
    }
}
//此微信并没有账户的情况下跳转页面进行登录注册账户绑定微信
echo "<script>alert('您还没有注册账户，请根据引导完成注册绑定');location.href='https://pay.hispot.cn/gitscan/h5/login.php?openid=".$authorize_token['openid']."'</script>";
exit;
        //获取用户授权的access_token
        function authorize_token($code=''){
                if (empty($code)) {
                        return "授权失败";
                        exit;
                }
                $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2de38da107527240&secret=446fdd6335e31f0ceeaf63562ff03a4c&code=".$code."&grant_type=authorization_code";
                return json_decode(file_get_contents($token_url),true);
        }
        //获取微信公众平台调用接口的access_token
        function voucher_token(){  
                        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx2de38da107527240&secret=446fdd6335e31f0ceeaf63562ff03a4c";
                        $access_token = json_decode(file_get_contents($url),true);   
                        return $access_token;
        }
        //获取用户信息
        function get_user_info($access_token,$openid){
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
                return json_decode(file_get_contents($url),true);
        }    
        //将用户openid与设备sn号景行对应入库
        function weixin_binding_sn($openid,$sn){
			$pdo = new PDO('mysql:host=localhost;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
            $pdo->exec('set names utf8');
            //查询此微信号是否已经于此sn号进行过绑定 Hispot1!
            $select_sn = "SELECT * FROM binding WHERE openid = '".$openid."' AND device_sn = '".$sn."'";
            $select_sn_data = $pdo->query($select_sn)->fetch(PDO::FETCH_ASSOC);
            if (!empty($select_sn_data)) {
                    return false;
            }
            //查询此sn号是否被其他微信号绑定过
            $select_sql = "SELECT * FROM binding WHERE device_sn = '".$sn."'";
            $select_data = $pdo->query($select_sql)->fetch(PDO::FETCH_ASSOC);
            if (!empty($select_data)) {
                 //绑定过进行删除
                 $delete_sql = "DELETE FROM binding WHERE device_sn = '".$sn."'";
                 $pdo->exec($delete_sql);   
            }
            //没有于其他微信号绑定过直接绑定此微信号
            $time = time();
            $sql = "INSERT INTO binding(openid,device_sn,`time`) VALUES('$openid','$sn','$time')";
			$pdo->exec($sql);
        }
        //向用户推送模板消息 告知用户绑定成功
        function sendMessage($openid,$token,$sn) {
            $judge = substr($sn,0,2);
            if ($judge == 'H2') {
                $type = "HiSpot-2";
            }else if($judge == 'D1'){
                $type = "大画-D1";
            }else{
                 $type = "HiSpot-2";
            }
            $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
            $post_data = array(
                "touser"=>$openid,
                "template_id"=>"DsuGBSBQ3NEQ0eciiikpgWSHMxhtYJO4IHVfxA_d0vY",
                // "url"=>"http://www.baidu.com",
                "data"=> array(
                        "first" => array(
                            "value"=>"注册成功通知！",
                            "color"=>"#173177"
                            ),
                        "keyword1"=>array(
                            "value"=>$type,
                            "color"=>"#173177"
                            ),
                        "keyword2"=>array(
                            "value"=>$sn,
                            "color"=>"#173177"
                            ),
                        "keyword3"=> array(
                            "value"=>date('Y-m-d H:i:s'),
                            "color"=>"#173177"
                            ),
                        "remark"=> array(
                            "value"=>"请于二十四小时内登陆设备完成设备绑定!",
                            "color"=>"red"
                            ),
                )
            );
            curl_post($url,json_encode($post_data));
        }
        //模拟post请求
        function curl_post($url,$data){ // 模拟提交数据函数
		$ch = curl_init ();
                curl_setopt ( $ch, CURLOPT_URL, $url );
                curl_setopt ( $ch, CURLOPT_POST, 1 );
                curl_setopt ( $ch, CURLOPT_HEADER, 0 );
                curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
                curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
                $return = curl_exec ( $ch );
                curl_close ( $ch );
        }    
        //检测此微信用户是否绑定账户
        function check_openid_binding_account($openid){
                $pdo = new PDO('mysql:host=localhost;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
                $pdo->exec('set names utf8');
                $select_sql = "SELECT * FROM user WHERE openid = '".$openid."'";
                $account_data = $pdo->query($select_sql)->fetch(PDO::FETCH_ASSOC);
                if (empty($account_data)) {
                        return false;            
                }else{
                        return true;
                }
        }  

     function data_synchro_old_database($openid){
		$user_data = get_new_user_data($openid);
		//将新登录的信息同步到旧数据库中的登录信息表
        $pdo_user_old = pdo_connect_old_user_database();
        $tel = $user_data['tel'];
        //旧数据库中存在此号码的数据进行删除
        $sql = "SELECT * FROM uc_members WHERE username = '$tel'";
        $data = $pdo_user_old->query($sql)->fetch(PDO::FETCH_ASSOC);
        if ($data) {
            // $delete_sql = "DELETE FROM uc_members WHERE username = '$tel'";
            // $pdo_user_old->exec($delete_sql);
            $uid = $data['uid'];
        }else{
            $password = $user_data['password'];
            $salt = substr(md5(rand('1','1000')),0,6);
            $old_password = md5($password.$salt);
            $insert_old_user_sql = "INSERT INTO uc_members(username,password,salt,phone) VALUES('$tel','$old_password','$salt','$tel')";
            $pdo_user_old->exec($insert_old_user_sql);
            $uid = $pdo_user_old->lastInsertId();
        } 
		
         //获取新数据库中的绑定信息
        $pdo = new PDO('mysql:host=localhost;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
        $pdo->exec('set names utf8');
        $select_binding_sql = "SELECT * FROM binding WHERE openid = '$openid' ORDER BY b_id DESC";
        $new_binding_data = $pdo->query($select_binding_sql)->fetch(PDO::FETCH_ASSOC);
            // file_put_contents("./data.log",$new_binding_data);

        //将新数据的绑定信息同步旧数据库的绑定信息表中
        $pdo_binding_old = pdo_connect_old_binidng_database();
        $sn = $new_binding_data['device_sn'];
        $time = date("Y-m-d H:i:s");
        $select_old_binding_sql = "SELECT * FROM weixin_binging WHERE Uid = '$uid' AND OpinID = '$openid' AND DeviceSelf = '$sn'";
        $old_binding_data = $pdo_binding_old->query($select_old_binding_sql)->fetch(PDO::FETCH_ASSOC);
        if (!$old_binding_data) {
            $insert_old_binidng_sql = "INSERT INTO weixin_binging(Uid,OpinID,CreateTime,DeviceSelf) VALUES('$uid','$openid','$time','$sn')";
            $pdo_binding_old->exec($insert_old_binidng_sql);   
        }

        //最后将uid和openid关联添加weixin_user表中 添加之前先通过uid以及openid来查询关联数据是否已经存在
        $select_relation_data_sql = "SELECT * FROM weixin_user WHERE openId = '$openid' AND user = '$uid'";
        $relation_data = $pdo_binding_old->query($select_relation_data_sql)->fetch(PDO::FETCH_ASSOC);
        //如果数据不存在
        if (!$relation_data) {
            //将uid和openid关联存在weixin_user表中
            $insert_old_relation_sql = "INSERT INTO weixin_user(openId,user) VALUES('$openid','$uid')";
            $pdo_binding_old->exec($insert_old_relation_sql); 
        }
    }

    //获取新数据库中的用户登录信息 
    function get_new_user_data($openid){
        $pdo = new PDO('mysql:host=localhost;dbname=device_binding','root','zqVnUy6cxsQXbpEZ');
        $pdo->exec('set names utf8');
        $select_user_sql = "SELECT * FROM user WHERE openid = '$openid'";
        $user_data = $pdo->query($select_user_sql)->fetch(PDO::FETCH_ASSOC);
        return $user_data;
    }

    //pdo连接旧用户登录信息库
    function pdo_connect_old_user_database(){
        $pdo_user_old = new PDO('mysql:host=123.57.16.97;dbname=ucenter','root','zqVnUy6cxsQXbpEZ');
        $pdo_user_old->exec('set names utf8'); 
        return $pdo_user_old;
    }

    //pdo连接旧用户绑定表
    function pdo_connect_old_binidng_database(){
        $pdo_binding_old = new PDO('mysql:host=123.57.16.97;dbname=wx_online_movie','root','zqVnUy6cxsQXbpEZ');
        $pdo_binding_old->exec('set names utf8');
        return $pdo_binding_old;
    }

?>
